package grib2handler.grib.ftp;

import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.log4j.Logger;

public abstract class Pool<FTPClient> {
	private final static Logger logger = Logger.getLogger( Pool.class );

	private final GenericObjectPool internalPool;
	
	public Pool(GenericObjectPool.Config poolConfig, PoolableObjectFactory factory)  
	{
	    this.internalPool = new GenericObjectPool(factory, poolConfig);  
	}
	
	public FTPClient getResource(){
		try{
			return (FTPClient)this.internalPool.borrowObject();
		}catch(Exception e){
			logger.error("ftp连接获取失败" + e.getMessage());
			return null;
		}
	}
	
	public void returnResource(FTPClient resource){
	    try {
	    	this.internalPool.returnObject(resource);
	    }catch (Exception e) {
	    	logger.error("ftp连接返还失败" + e.getMessage());
	    }
	}
	
	public void destroy(){
	    try{
	    	this.internalPool.close();  
	    }catch (Exception e) {
	    	logger.error("ftp连接池销毁失败" + e.getMessage());
	    }
	}
	
	public void clear(){
	    try{
	    	this.internalPool.clear();  
	    }catch (Exception e) {
	    	logger.error("ftp连接池清空失败" + e.getMessage());
	    }
	}
	
	public void delResource(FTPClient resource) {
		try{
	    	this.internalPool.invalidateObject(resource);
	    }catch (Exception e) {
	    	logger.error("ftp连接删除失败" + e.getMessage());
	    }
	}
	
	public int inPoolSize(){
		try{
			return this.internalPool.getNumIdle();
		}catch(Exception e){
	    	logger.error("ftp连接池初始化失败" + e.getMessage());
			return 0;
		}
	}
	
	public int borrowSize(){
		try{
			return this.internalPool.getNumActive();
		}catch(Exception e){
	    	logger.error("ftp连接池初大小获取失败" + e.getMessage());
			return 0;
		}
	}
}
